package org.unisinos.gc.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionError;
import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.unisinos.gc.dao.CongressoDAO;
import org.unisinos.gc.form.CongressoForm;
import org.unisinos.gc.validation.CongressoValidation;
import org.unisinos.gc.vo.Congresso;

public class SaveCongressoAction extends Action {
	
	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		super.execute(mapping, form, request, response);

		ActionErrors errors = new ActionErrors();
		ActionForward forward = null;
		
		CongressoForm congressoForm = (CongressoForm)form;
		
		String valid = CongressoValidation.validateUpdate(congressoForm);
		
		if (valid == null || valid.equals("")) {
			Congresso congresso = congressoForm.toCongresso();
			CongressoDAO.updateCongresso(congresso);
			
			CongressoDAO.deleteCongressoArea(congresso.getId());

			for(Integer codigoArea : congressoForm.getIdAreaList()){
				CongressoDAO.insertCongressoArea(congresso.getId(), codigoArea);
			}
			
			forward = mapping.findForward("success");
		}else {
			errors.add(ActionErrors.GLOBAL_ERROR, new ActionError("systemError.msg",valid));
		}

		if (!errors.isEmpty()) {
			super.saveErrors(request, errors);
			forward = mapping.findForward("error");
		}
		request.setAttribute("mode", "edit");
		return forward;
	}
	
}
